package cn.tedu.sk.service.impl;

import cn.tedu.sk.entity.UserInfo;
import cn.tedu.sk.entity.param.LoginInfoParam;
import cn.tedu.sk.service.LoginService;
import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Jwts;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Value("${cifer.jwt.key}")
    private String jwtKey;

    private Long durationInMinute;
    //Spring Security中进行身份验证的是AuthenticationManager接口，
    // ProviderManager是它的一个默认实现
    @Autowired
    private AuthenticationManager authenticationManager;



    @Override
    public String login(LoginInfoParam loginInfoParam) {
        log.debug("开始验证授权");
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                loginInfoParam.getUsername(),
                loginInfoParam.getPassword()
        );

        Authentication authenticateResult = authenticationManager.authenticate(authentication);

        Object principal = authenticateResult.getPrincipal();
        UserInfo userInfo = (UserInfo) principal;

        Collection<GrantedAuthority> authorities = userInfo.getAuthorities();

        //生成jwt
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("username", userInfo.getUsername());
        claims.put("authorization", JSON.toJSONString(authorities));

        String jwt = Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60))
                .signWith(SignatureAlgorithm.HS256, jwtKey)
                .compact();
        log.debug("生成的jwt为：{}", jwt);
        //TODO  jwt的保存

        // localStorage.setItem('loginInfo', loginInfoJsonString);
        //jwt的数据被前端保存
        return jwt;
    }
}
